<?php

namespace app\api\lists;


use app\common\model\finance\TransactionRecord;
use app\common\lists\ListsSearchInterface;


/**
 * transaction列表
 * Class TransactionRecordLists
 * @package app\api\lists
 */
class TransactionMonthlyReportLists extends BaseApiDataLists implements ListsSearchInterface
{


    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author likeadmin
     * @date 2025/04/09 14:11
     */
    public function setSearch(): array
    {
        return ['month'];
    }

    public function queryWhere()
    {
        // 指定客户
        $where[] = ['group_id', '=', $this->userInfo['group_id']];
        // 指定月份
        if (isset($this->params['month'])) {
            $where[] = function($query) {
                $query->whereRaw('DATE_FORMAT(transaction_date, "%Y-%m") = ?', [$this->params['month']]);
            };
        }
        // 交易类型条件
        $where[] = ['transaction_type', 'in', ['CARD_PAYMENT', 'CLEARING', 'settled', 'pending', 'AUTHORIZATION']];
        // 状态条件
        $where[] = ['status', 'in', ['SUCCESS', 'CANCELLED', 'settled', 'posted', 'pending']];
        return $where;
    }

    /**
     * @notes 获取transaction列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author likeadmin
     * @date 2025/04/09 14:11
     */
    public function lists(): array
    {
        $list = TransactionRecord::field([
            'DATE_FORMAT(transaction_date, "%Y-%m") as transaction_date',
            'COUNT(*) as transaction_count',
            'SUM(ABS(service_amount)) as service_amount',
            'SUM(ABS(transaction_amount)) as transaction_amount',
            'SUM(ABS(billing_amount)) as billing_amount'
        ])
            ->where($this->queryWhere())
            ->withSearch($this->setSearch(), $this->params)
            ->group('DATE_FORMAT(transaction_date, "%Y-%m")') // 按年月分组
            ->order('transaction_date DESC') // 按年月排序
            ->select()
            ->toArray();
        // 修改billing_amount
       // foreach ($list as &$item) {
           // $item['billing_amount'] = floatval($item['billing_amount']) + floatval($item['service_amount']);
        //}
        unset($item);
        return $list;
    }


    /**
     * @notes 获取transaction数量
     * @return int
     * @author likeadmin
     * @date 2025/04/09 14:11
     */
    public function count(): int
    {
        return TransactionRecord::group('DATE(transaction_date), user_id')
            ->where($this->queryWhere())
            ->withSearch($this->setSearch(), $this->params)
            ->group('DATE_FORMAT(transaction_date, "%Y-%m")') // 按年月分组
            ->count();
    }

}